package nju.software.xkxt.web.json;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Http响应的构造器
 * 
 * @author typ
 * 
 */
public class ResponseBuilder {

	/**
	 * 默认的字符集
	 */
	private static final String DEFAULT_CHARSET = "utf-8";

	/**
	 * 返回Json格式的结果
	 * 
	 * @param response
	 *            http响应对象
	 * @param content
	 *            响应内容
	 * @throws Exception
	 */
	public void writeJsonResponse(HttpServletResponse response, String content)
			throws Exception {
		response.addHeader("Content-Type", "application/json;charset="
				+ DEFAULT_CHARSET);
		response.setCharacterEncoding(DEFAULT_CHARSET);
		PrintWriter writer = response.getWriter();
		writer.write(content);
		writer.flush();
		writer.close();
	}

	/**
	 * 将某个对象转换为Json返回
	 * 
	 * @param response
	 * @param o
	 * @throws Exception
	 */
	public void writeJsonResponse(HttpServletResponse response, Object o)
			throws Exception {
		Gson gson = new Gson();
		String strJson = gson.toJson(o);
		writeJsonResponse(response, strJson);
	}

	/**
	 * 将操作结果转换成json格式返回
	 * 
	 * @param response
	 *            http响应对象
	 * @param objects
	 * @throws Exception
	 */
	public void writeJsonResponseDm(HttpServletResponse response,
			List<Object> objects) throws Exception {
		Gson gson = new Gson();
		String strJson = gson.toJson(objects);
		writeJsonResponse(response, strJson);
	}

}